<?php //pack11class

class CurrencyManager {
    
    private static $currenciesByID=array();
    private static $currenciesByName=array();
    
    private static $currenciesDone=false;
    private static $dataLoaded=false;

    private static $current=0;

    const SOURCE="http://www.bank.lv/vk/xml.xml";

    public static function currentCurrency() {
        array_push(Tracer::$traceFrom,__CLASS__);
        if(array_key_exists("currency", $_SESSION)) self::$current=self::getCurrency($_SESSION["currency"]);
        $setting=SettingsManager::getSetting("currency");
        if($setting) self::$current=self::getCurrency($setting->value);
        if(get_class(self::$current)!="Currency") self::$current=self::getCurrency(2);
       //trace("----------------------".self::$current);
        return self::$current;
    }

    public static function getCurrencies($byName=false) {
        
        if(self::$currenciesDone) return ($byName)? self::$currenciesByName:self::$currenciesByID;

        if(!self::$dataLoaded) self::getDataFromSource();

        $currencies=MySQLGet::process("Select * from ".MySQL::TABLE_CURRENCY." where `active`='1';");
        foreach($currencies as $item) {
            $currency=new Currency();
            $currency->setFromSQL($item);
            self::$currenciesByID[$currency->id]=$currency;
            self::$currenciesByName[$currency->system]=$currency;
        }
        self::$currenciesDone=true;
        return ($byName)? self::$currenciesByName:self::$currenciesByID;
    }

    public static function getCurrency($id) {
        if(!self::$currenciesDone) self::getCurrencies();
        if(is_numeric(0+$id)) {
            if(array_key_exists($id,self::$currenciesByID)) return self::$currenciesByID[$id];
        } else {
            if(array_key_exists($id,self::$currenciesByName)) return self::$currenciesByName[$id];
        }
        return false;
    }

    public static function getDataFromSource() {
        $currencySeting=SettingsManager::getSetting("currency");
        if(!is_numeric($currencySeting->value)) $currencySeting->value=self::$current;
        if(self::$dataLoaded) {
            //echo "data Loaded";
            return true;
        }
        $date=MySQLGet::process("Select `updated` from ".MySQL::TABLE_CURRENCY." where `active`='1' limit 1;");
        //trace($date[0]["updated"]." ".date("Y-m-d"));
        if($date[0]["updated"]!=date("Y-m-d")){
            $xml =  @simplexml_load_file(self::SOURCE);
            if(!$xml) return false;
            $cases=array();
            foreach($xml->Currencies[0] as $node) {
                array_push($cases, "WHEN '".$node->ID."' THEN ".$node->Rate);
            }
            MySQLSet::process("Update ".MySQL::TABLE_CURRENCY." set `rate`=(case `system` ".implode(" ",$cases)." else 1 end), `updated`=CURRENT_TIMESTAMP;");
        }
        self::$dataLoaded=true;
    }

    public static function getValue($value,$id=0,$list=false) {
        $returnValue=$value;
        $usedCurrency=($list)? self::currentCurrency():self::getCurrency($id);
        $currentCurrency=($list)?self::getCurrency($id):self::currentCurrency();
        if(!$usedCurrency) { trace("Used currency at id $id not defined"); return false; }
        if(!$currentCurrency) { trace("Current currency not defined"); return false; }
        if($usedCurrency->id==$currentCurrency->id) {
            //trace("uc=cc");
            //trace($value." usedCurrency:".$usedCurrency->id." (".$usedCurrency->rate."); currentCurrency:".$currentCurrency->id."(".$currentCurrency->rate."); ".$returnValue);
            return self::getRound($value);
        }
        if($usedCurrency->id==1 || $currentCurrency->id==1) {
            if($usedCurrency->id==1) {
                $returnValue=$value*($currentCurrency->rate*$currentCurrency->units);
                //trace("uc1");
                //trace($value." usedCurrency:".$usedCurrency->id." (".$usedCurrency->rate."); currentCurrency:".$currentCurrency->id."(".$currentCurrency->rate."); ".$returnValue);
            }
            if($currentCurrency->id==1) {
                //trace("cc1");
                $returnValue=$value*($usedCurrency->rate*$usedCurrency->units);
                //trace($value." usedCurrency:".$usedCurrency->id." (".$usedCurrency->rate."); currentCurrency:".$currentCurrency->id."(".$currentCurrency->rate."); ".$returnValue);
            }
        } else {
            $returnValue=$value*($currentCurrency->rate*$currentCurrency->units)/($usedCurrency->rate*$usedCurrency->units);
            //trace("both");
            //trace($id." \$value*({$currentCurrency->rate}*{$currentCurrency->units})/({$usedCurrency->rate}*{$usedCurrency->units}");
        }
        //trace($value." usedCurrency:".$usedCurrency->id." (".$usedCurrency->rate."); currentCurrency:".$currentCurrency->id."(".$currentCurrency->rate."); ".$returnValue);
                //trace($value." ".$returnValue);
        return self::getRound($returnValue);
    }

    private static function getRound($value) {
        //array_push(Tracer::$traceFrom,__CLASS__);
        if(!is_numeric($value)) {
            //trace("not numeric");
            return 0;
        }
        $len=strlen(round($value,0));
        if($len>=7) {
            //trace(">7: ".round(ceil($value/100)*100,-2));
            return round(ceil($value/100)*100,-2);
        } else if($len<=3) {
            //trace("<3: ".round($value,2));
            return round($value,2);
        } else {
            //trace("else: ".round($value,0));
            return round($value,0);
        }
        //trace("not any");
        return $value;
    }

    public static function getAllVariants($value) {
        $result=array();
        foreach(self::getCurrencies() as $currency) {
            array_push($result,new CurrencyValue($currency->id,self::getValue($value, $currency->id,true)));
        }
        return $result;
    }

}
?>
